<template>
  <div class="message-tree">
    <!-- 留言输入框 -->
    <el-card class="message-input" shadow="always">
      <el-form ref="newMessageForm" :model="newMessageForm" :rules="newMessageRules">
        <el-form-item prop="newMessage">
          <el-input
            type="textarea"
            v-model="newMessageForm.newMessage"
            placeholder="请输入留言（3~200字）"
            :rows="3"
            maxlength="200"
            show-word-limit
          />
          <div style="text-align: right; margin-top: 10px;">
            <el-button type="primary" @click="submitMessage">发布留言</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 留言树结构 -->
    <div class="message-list">
      <message-item
        v-for="item in messages"
        :key="item.id"
        :message="item"
        @reply="handleReply"
        @refresh="loadMessages"
      />
    </div>
  </div>
</template>

<script>
import MessageItem from './MessageItem.vue'
import { listMessage, publishMessage } from "@/api/message/message";

export default {
  components: { MessageItem },
  data() {
    return {
      messages: [], // 初始留言列表
      newMessageForm: {
        newMessage: '',
      },
      newMessageRules: {
        newMessage: [
          { required: true, trigger: "blur", message: "留言不能为空" },
          { min: 3, max: 200, message: "请输入留言（3~200字）", trigger: "blur" }
        ],
      },
    }
  },
  created() {
    this.loadMessages()
  },
  methods: {
    loadMessages() {
      listMessage().then(res => {
        this.messages = res.messages
      })
    },
    submitMessage() {
      this.$refs.newMessageForm.validate(valid => {
        if (valid) {
          publishMessage(-1, this.newMessageForm.newMessage).then(res => {
            this.loadMessages()
          })
          this.newMessageForm.newMessage = ''
        }
      })
    },
    handleReply(parentId, replyContent) {
      const findAndInsert = (list) => {
        for (let item of list) {
          if (item.id === parentId) {
            item.children.push({
              id: Date.now(),
              content: replyContent,
              username: '当前用户',
              updateTime: new Date().toLocaleString(),
              children: []
            })
            return true
          } else if (item.children?.length) {
            if (findAndInsert(item.children)) return true
          }
        }
        return false
      }
      findAndInsert(this.messages)
    }
  }
}
</script>

<style scoped>
.message-tree {
  max-width: 800px;
  margin: 0 auto;
}
.message-input {
  margin-bottom: 20px;
}
</style>
